package com.xuwl.service.impl;

import com.xuwl.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * ┏┛ ┻━━━━━┛ ┻┓
 * ┃　　　━　　　┃
 * ┃　┳┛　  ┗┳　┃
 * ┃　　　　　　 ┃
 * ┃　　　┻　　　┃
 * ┗━┓　　　┏━━━┛
 * ┃　　　┃   神兽保佑,代码无BUG！
 * ┃　　　┗━━━━━━━━━┓
 * ┃　　　　　　　   ┣┓
 * ┃　　　　        ┏┛
 * ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛
 * ┃ ┫ ┫   ┃ ┫ ┫
 * ┗━┻━┛   ┗━┻━┛
 * Created by xuwl on 2018/5/17.
 */
@Service
public class RedisServiceImpl implements RedisService {
    private static final String REDIS_KEY = "TEST_REDIS_KEY";
    @Autowired
    protected RedisTemplate redisTemplate;
    @Resource
    protected HashOperations hashOperations;


    @Override
    public String getRedisKey() {
        return this.REDIS_KEY;
    }

    @Override
    public void put(String key, Object doamin, long expire) {
        hashOperations.put(getRedisKey(), key, doamin);
        if (expire != -1) {
            redisTemplate.expire(getRedisKey(), expire, TimeUnit.SECONDS);
        }
    }

    @Override
    public void remove(String key) {
        hashOperations.delete(getRedisKey(), key);
    }

    @Override
    public Object get(String key) {
        return hashOperations.get(getRedisKey(), key);
    }

    @Override
    public List getAll() {
        return hashOperations.values(getRedisKey());
    }

    @Override
    public Set<String> getKeys() {
        return hashOperations.keys(getRedisKey());
    }

    @Override
    public boolean isKeyExists(String key) {
        return hashOperations.hasKey(getRedisKey(), key);
    }

    @Override
    public long count() {
        return hashOperations.size(getRedisKey());
    }

    @Override
    public void empty() {
        Set<String> set = hashOperations.keys(getRedisKey());
        set.stream().forEach(key -> hashOperations.delete(getRedisKey(), key));
    }
}
